package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.CommonApplicationTemplate;
import com.wuseguang.springcloud.service.CommonApplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonApplicationServiceImpl implements CommonApplicationService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CommonApplicationTemplate commonApplicationTemplate;


    /**
     * @描述 查询该用户所有的一级菜单名称和二级菜单名称
     * @创建人 zm
     * @创建时间 2019/12/1
     */
    @Override
    public Map<String, List<Map<String, Object>>> queryFunctionFindAll(String admin, String schoolId, String teacherId, Integer type) {
        Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
        String sql1 = "SELECT jurisdiction_id STRING FROM teacher_commonapplication WHERE teacher_id=? ORDER BY opertime";
        List<Integer> integers = commonApplicationTemplate.queryListInteger(sql1, new Object[]{teacherId});
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        if ("0".equals(admin)) {
            //查询功能权限
            String sql = "SELECT*FROM  (select id,name,pid ,if(count(1)>1,1,0) as state,image,router from ( " +
                    "  select id,name,pid,image,w_router  router  from jurisdiction where  pid =? AND web=1 UNION all " +
                    "  select jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid ,'0','' from school_jurisdiction" +
                    " where jurisdiction_pid = ? " +
                    " and school_id=? AND web=1 " +
                    "   ) jurisdiction group by id ) s WHERE s.state=1 ORDER BY id";

            logger.info("管理员查询功能权限 sql= {},参数1 = {}，参数2 = {},参数3 = {}", 0, 0, schoolId);

            List<Map<String, Object>> list = commonApplicationTemplate.queryListMap(sql, 0, 0, schoolId);
            //循环一级权限
            for (Map<String, Object> s : list) {//添加二级菜单，信息
                List<Map<String, Object>> maps1 = new ArrayList<Map<String, Object>>();
                List<Map<String, Object>> twoList = commonApplicationTemplate.queryListMap(sql, s.get("id"), s.get("id"), schoolId);
                int id1 = (int) s.get("id");
                if (twoList != null && twoList.size() > 0 && integers != null && integers.size() > 0) {
                    logger.info("twoList={}", twoList.toString());
                    for (Map<String, Object> stringObjectMap : twoList) {//查询二级菜单是否包含有
                        Integer id = (Integer) stringObjectMap.get("id");
                        logger.info("id={}", id);
                        if (integers.contains(id)) {
                            maps.add(stringObjectMap);
                        } else {
                            maps1.add(stringObjectMap);
                        }
                    }
                    s.put("list", maps1);
                } else {
                    s.put("list", twoList);
                }
            }
            logger.info("管理员。。。");
            map.put("applicationfunction", list);
            map.put("commonfunctions", maps);
            return map;
        } else {
            //查询功能权限
            String sql = " SELECT*FROM  (  SELECT id,name,pid ,IF(COUNT(1)>1,1,0) AS state,image,router  FROM ( " +
                    "               SELECT id,name,pid,image,w_router  router   FROM jurisdiction WHERE  pid =? AND web=1 UNION  ALL " +
                    "                SELECT jurisdiction_id  id ,jurisdiction_name name,jurisdiction_pid pid,'0','' FROM grouping_jurisdiction rj " +
                    "                WHERE EXISTS(SELECT * FROM roles r LEFT JOIN teacher_role t ON(r.id=t.role_id)  WHERE t.teacher_id =? " +
                    "                 AND r.grouping_id=rj.grouping_id ) AND  jurisdiction_pid =? AND rj.school_id =? GROUP BY jurisdiction_id " +
                    "             ) jurisdiction GROUP BY id ) s WHERE s.state=1 ORDER BY id ";

            logger.info("非管理员查询功能权限 sql= {},参数1 = {}，参数2 = {},参数3 = {}", 0, teacherId, 0);
            //一级权限
            List<Map<String, Object>> list = commonApplicationTemplate.queryListMap(sql, 0, teacherId, 0, schoolId);
            //循环一级权限
            for (Map<String, Object> s : list) {
                List<Map<String, Object>> maps1 = new ArrayList<Map<String, Object>>();
                List<Map<String, Object>> twoList = commonApplicationTemplate.queryListMap(sql, s.get("id"), teacherId, s.get("id"), schoolId);
                if (twoList != null && twoList.size() > 0 && integers != null && integers.size() > 0) {
                    for (Map<String, Object> stringObjectMap : twoList) {
                        Integer id = (Integer) stringObjectMap.get("id");
                        logger.info("id={}", id);
                        if (integers.contains(id)) {
                            maps.add(stringObjectMap);
                        } else {
                            maps1.add(stringObjectMap);
                        }
                    }
                    s.put("list", maps1);
                } else {
                    s.put("list", twoList);
                }
            }
            logger.info("不是管理员。。。");
            map.put("applicationfunction", list);
            map.put("commonfunctions", maps);
            return map;
        }
    }

    /**
     * @描述 查询常用功能
     * @创建人 zm
     * @创建时间 2019/12/1
     */
    @Override
    public List<Map<String, Object>> queryFunction(String admin, String schoolId, String teacherId) {
        Map<String, List<Map<String, Object>>> stringListMap = queryFunctionFindAll(admin, schoolId, teacherId, 0);
        return stringListMap.get("commonfunctions");
    }

    /**
     * @描述 添加常用功能
     * @创建人 zm
     * @创建时间 2019/12/1
     */
    @Override
    public int addFunction(String schoolId, String teacherId, Integer[] ids) {
        String sql = " DELETE FROM teacher_commonapplication WHERE school_id=? AND  teacher_id=? ";
        commonApplicationTemplate.updateByParameter(sql, schoolId, teacherId);
        if (ids == null || ids.length == 0) {
            return 1;
        } else {
            String sql1 = " INSERT INTO teacher_commonapplication(jurisdiction_id,school_id,teacher_id,opertime) VALUES(?,?,?,now())";
            try {
                return commonApplicationTemplate.batchUpdate(sql1, ids, schoolId, teacherId).length;
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
            }
            return 0;
        }
    }
}
